package com.itheima.reggie.controller;

import com.itheima.reggie.common.Result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        log.info(file.toString());
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取原始文件名后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID拼接后缀名生成文件名
        String fileName = UUID.randomUUID() + suffix;
        //判断路径是否存在
        File dir = new File(basePath);
        if (!dir.exists()) {
            //如果不存在就要创建
            dir.mkdirs();
        }
        //将文件转存到磁盘中
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //给前端返回文件名
        return Result.success(fileName,"上传成功");
    }

    /**
     * 文件下载：文件上传到网页后，能立马在页面回显
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        log.info(name);
        try {
            //用输入流读取上传的文件
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //用输出流写出来，响应到页面
            ServletOutputStream outputStream = response.getOutputStream();
            //指定返回类型
            response.setContentType("image/jpeg");
            int len;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
